﻿using System;
using Newtonsoft.Json.Linq;
using TrinityAPI.Base;
using TrinityAPI.Base.Tools;
using TrinityAPI.Base.Models;
using DouYin.Open.Platform.Tools;

namespace DouYin.Open.Platform
{
    public class GetOrderSensitiveInfo : IAction
    {
        public JToken Invoke(JObject dataset, params JToken[] args)
        {
            try
            {
                var request = dataset.GetJsonObject("request");
                var constant = dataset.GetJsonObject("constant");

                string eShopCode = request.GetJsonObjectStringValue("eShopCode");
                string orderId = request.GetJsonObjectStringValue("orderId");

                var douyinAPIConfig = constant.GetJsonObject("douyinAPIConfig");
                var eshopAPIConfig = douyinAPIConfig.GetJsonObject("eshops").GetJsonObject(eShopCode);

                int type = douyinAPIConfig.GetJsonObjectIntValue("type");
                string url = douyinAPIConfig.GetJsonObjectStringValue("url");
                string appKey = eshopAPIConfig.GetJsonObjectStringValue("app_key");
                string appSecret = eshopAPIConfig.GetJsonObjectStringValue("app_secret");
                var timeout = eshopAPIConfig.GetJsonObjectIntValue("timeout", 60000);
                var proxy = eshopAPIConfig.GetJsonObjectValue("proxy");

                if (string.IsNullOrWhiteSpace(eShopCode))
                    throw new ArgumentNullException("eShopCode");

                if (string.IsNullOrWhiteSpace(url))
                    throw new ArgumentNullException("url");

                if (string.IsNullOrWhiteSpace(appKey))
                    throw new ArgumentNullException("app_key");

                if (string.IsNullOrWhiteSpace(appSecret))
                    throw new ArgumentNullException("app_secret");

                string timestamp = ApiUtils.GetTimeStamp(DateTime.Now).ToString();
                string accessToken = type == 1 ? GetAccessToken.GetToken(eShopCode, constant) : eShopCode;
                string strParam = "{\"shop_order_id\":\"" + orderId + "\"}";

                string api = null;
                string method = "order.orderDetail";
                string version = "2";
                string sign_method = "hmac-sha256";
                string sign = ApiUtils.Sign(appKey, appSecret, method, timestamp, version, strParam);

                if (type == 1)
                {
                    if (!url.EndsWith("/"))
                        url = url + "/";
                    if (string.IsNullOrWhiteSpace(api))
                        api = method.Replace(".", "/");
                    else if (api.StartsWith("/"))
                        api = api.Trim('/');
                    url = string.Format("{0}{1}?app_key={2}&method={3}&v={4}&sign={5}&timestamp={6}&access_token={7}&sign_method={8}", url, api, appKey, method, version, sign, timestamp, accessToken, sign_method);
                }
                else
                {
                    if (!url.EndsWith("/"))
                        url = url + "/";
                    if (!string.IsNullOrWhiteSpace(api))
                        api = "&api=" + System.Web.HttpUtility.HtmlEncode(api);
                    url = string.Format("{0}getOrderSensitive?app_key={1}&method={2}&v={3}&sign={4}&timestamp={5}&access_token={6}&sign_method={7}{8}", url, appKey, method, version, sign, timestamp, accessToken, sign_method, api);
                }

                var headers = new System.Collections.Generic.Dictionary<string, string>() { { "content-type", "application/json" } };
                LogHelper.Info("url: " + url, "PlatformApiLog");
                LogHelper.Info("request: " + strParam, "PlatformApiLog");
                string responseString = HttpHelper.HttpWebRequest(url, strParam, "POST", timeout, headers, proxy?.ToString());
                LogHelper.Info("response: " + responseString, "PlatformApiLog");

                var responseObject = JObject.Parse(responseString);
                if (responseObject.GetJsonObjectIntValue("code", 1) != 10000)
                {
                    string msg = responseObject.GetJsonObjectStringValue("msg");
                    string sub_msg = responseObject.GetJsonObjectStringValue("sub_msg");
                    throw ExceptionHelper.GenException("@E110000002", msg + (string.IsNullOrWhiteSpace(sub_msg) ? "" : "-" + sub_msg));
                }

                var orderDetail = responseObject.GetJsonObject("data").GetJsonObject("shop_order_detail");
                var postAddress = orderDetail.GetJsonObject("post_addr");

                var orderSensitiveInfo = new JObject();
                orderSensitiveInfo["orders_no"] = orderId;
                orderSensitiveInfo["receiver_name"] = orderDetail.GetJsonObjectStringValue("post_receiver");
                orderSensitiveInfo["receiver_province"] = postAddress.GetJsonObject("province").GetJsonObjectStringValue("name");
                orderSensitiveInfo["receiver_city"] = postAddress.GetJsonObject("city").GetJsonObjectStringValue("name");
                orderSensitiveInfo["receiver_district"] = postAddress.GetJsonObject("town").GetJsonObjectStringValue("name");
                orderSensitiveInfo["receiver_address"] = postAddress.GetJsonObjectStringValue("detail");
                orderSensitiveInfo["receiver_telephone"] = orderDetail.GetJsonObjectStringValue("post_tel");
                orderSensitiveInfo["receiver_mobile"] = orderDetail.GetJsonObjectStringValue("post_tel");
                orderSensitiveInfo["oaid"] = orderDetail.GetJsonObjectStringValue("open_address_id");
                return new JArray() { orderSensitiveInfo };
            }
            catch (BaseException ex)
            {
                if (!string.IsNullOrEmpty(ex.Message))
                    throw ex;
                throw new Exception(ex.Code);
            }
            catch (Exception ex)
            {
                LogHelper.Info("DouYin GetOrderSensitiveInfo fail: " + ex.Message);
                throw new Exception("@E110000001");
            }
        }
    }
}
